<?php

use think\Cache;
use think\Request;
// use think\cache\driver\Redis;
use app\model\SysconfigModel;


Class Wechat_OA{
    //微信验证token
    private $token = '0b60f61f01ba6cb292b8ce3b5e822fbc';
    //微信授权配置信息
    protected $appid;
    protected $appsecret;

    
    public function __construct(){    
        $this->appid = SysconfigModel::where('name','Wechat_Appid')->value('val');
        $this->appsecret = SysconfigModel::where('name','Wechat_Appsecret')->value('val');
    }
    
    
    public function get_user_info( $code ){
        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?';
        $param = 'appid='.$this->appid.'&secret='.$this->appsecret.'&code='.$code.'&grant_type=authorization_code';
        $result = get_by_curl( $url . $param);

        $data = json_decode($result);
        if(isset($data->openid) == false || isset($data->access_token) == false){
            return false;
        }

        $openid = $data->openid;
        $access_token = $data->access_token;
        // 获取当前用户信息
        $user_info = get_by_curl('https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN');
        $user_info = json_decode($user_info);

        return $user_info;     
    }


    public function get_share_config( $url ){
        $access_token = $this->get_access_token(); 
        if( $access_token == false ){
            return false;
        }
        
        // 获取jsapi_ticket
        $ticket = $this->get_ticket($access_token);
        if( $ticket == false ){
            return false;
        }

        // 生成noncestr
        $noncestr = $this->get_nonceStr();
        // 生成timestamp
        $timestamp = time();
        // -------- 生成签名 --------
        $share_config = [
            'noncestr' => $noncestr,
            'timestamp' => $timestamp,
        ];

        $string = "jsapi_ticket=$ticket&noncestr=$noncestr&timestamp=$timestamp&url=$url";
        $signature = sha1($string);
    
        // 计算签名
        $share_config['signature'] = $signature;
        $share_config['appid'] = $this->appid;
        $share_config['ticket'] = $ticket;


        return $share_config;
    }

    
    public function send_message($data){
        //模板消息
        $template = array(
            'touser'=>$data['openid'],  //用户openid
            'template_id'=>'2jwPvOoBfz2y8tmDpC1-PTQH60edqt0T8Z3bXRSufHs', //在公众号下配置的模板id
            'url'=>$data['url'], //点击模板消息会跳转的链接
            'topcolor'=>"#7B68EE",
            'data'=>array(
                'first'=>array('value'=>$data['title'],'color'=>"#000000"),
                'keyword1'=>array('value'=>$data['name'],'color'=>'#000000'),  //keyword需要与配置的模板消息对应
                'keyword2'=>array('value'=>$data['mobile'],'color'=>'#000000'),
                'keyword3'=>array('value'=>$data['visittime'],'color'=>'#000000'),
                'keyword4'=>array('value'=>$data['status'],'color'=>'#000000'),
                'remark' =>array('value'=>$data['remark'],'color'=>'#000000'), )
            );
        $json_template = json_encode($template,JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT);  
        // var_dump($json_template);
        $access_token = $this->get_access_token(); 
        $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$access_token;
        $result = $this->curl_post( $url,$json_template);
        $result = json_decode($result);

        if( $result->errcode == 0 ){
            return false;
        }

        return true;
    }


    /* 创建二维码 @param - $qrcodeID传递的参数，$qrcodeType二维码类型 默认为临时二维码 @return - 返回二维码图片地址*/
    public function create_qrcode($qrcodeID , $qrcodeType = 0){
        $access_token = $this->get_access_token(); 
        if($qrcodeType == 0){
            $qrcodeType = 'QR_SCENE';    
        }else{
            $qrcodeType = 'QR_LIMIT_SCENE';
        }        
        $json_template = '{"expire_seconds": 1800, "action_name": "'.$qrcodeType.'", "action_info": {"scene": {"scene_id": '.$qrcodeID.'}}}';
        $url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=".$access_token;
        $result = $this->curl_post( $url,$json_template);
        $data = json_decode($result);
        if(isset($data->ticket) == false){
            return false;
        }

        return 'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket='.$data->ticket;
       
    }


    /**
     * 获取JS证明
     * @param $access_token
     * @return mixed
     */
    private function get_ticket($access_token){
        // 获取缓存
        $ticket = Cache::get('Cache_Ticket','');
        // 缓存不存在-重新创建
        if (empty($ticket)) {
            // 获取js_ticket
            $url = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?';
            $param = 'access_token=' . $access_token . '&type=jsapi';
            $result = get_by_curl( $url . $param );
            $data = json_decode($result);
            
            if(isset($data->ticket) == false){
                return false;
            }
            // 保存至缓存
            $ticket = $data->ticket;
            //设置cookie
            Cache::set('Cache_Ticket' ,$ticket,7000);
        }
        return $ticket;
    }
 
    
    //通用access_token
    private function get_access_token(){
        // 获取缓存
        $access_token = Cache::get('Cache_Access_Token','');
        // 缓存不存在-重新创建
        if (empty($access_token)) {
            $url = 'https://api.weixin.qq.com/cgi-bin/token?';
            $param = 'appid='.$this->appid.'&secret='.$this->appsecret.'&grant_type=client_credential';
            $result = get_by_curl( $url . $param);
            $data = json_decode($result);
            // var_dump($data);
            if(isset($data->access_token) == false){
                return false;
            }
            $access_token = $data->access_token;
            //设置Cache
            Cache::set('Cache_Access_Token' ,$access_token,7000);
        }

        return $access_token;
    }


    private function get_nonceStr($length = 16) {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
          $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    /**
     * @param $url
     * @param array $data
     * @return mixed
     * curl请求
     */
    private function curl_post($url , $data=array()){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        // POST数据
        curl_setopt($ch, CURLOPT_POST, 1);
        // 把post的变量加上
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }
}



